import 'package:intl/intl.dart';

extension NumExt on num {
  ///保留小数点后几位，会4舍5入
  num? fixedOrNull(int fractionDigits) {
    final str = NumberFormat("#.${"#" * fractionDigits}").format(this);
    final intVal = int.tryParse(str);
    if (intVal != null) return intVal;
    var doubleVal = double.tryParse(str);
    if (doubleVal != null) return doubleVal;
    return null;
  }

  ///单位为m的数字带距离单位的字符串
  String get toDistance {
    if (this < 1000) {
      return "${toInt()}m";
    } else {
      //小数点最多2位，不补零
      return "${NumberFormat("#.##").format(this / 1000)}km";
    }
  }

  ///单位为m的数字带距离单位的字符串
  String get toDistanceCh {
    if (this < 1000) {
      return "${this.toInt()}米";
    } else {
      //小数点最多2位，不补零
      return "${NumberFormat("#.##").format(this / 1000)}千米";
    }
  }

  ///度数值转方位
  String get toBearing {
    // 先归一化到 0..359
    final angle = ((this % 360) + 360) % 360;
    if (angle >= 0 && angle <= 22.5 || angle > 337.5) {
      return "北";
    } else if (angle <= 67.5) {
      return "东北";
    } else if (angle <= 112.5) {
      return "东";
    } else if (angle <= 157.5) {
      return "东南";
    } else if (angle <= 202.5) {
      return "南";
    } else if (angle <= 247.5) {
      return "西南";
    } else if (angle <= 292.5) {
      return "西";
    } else if (angle <= 337.5) {
      return "西北";
    } else {
      return "北";
    }
  }

  ///经纬度，转度分
  String get toDM {
    final d = toInt();
    final ms = ((this - d) * 60);
    return "$d°${NumberFormat("#.##").format(ms.abs())}'";
  }

  ///经纬度，转度分秒
  String get toDMS {
    final d = toInt();
    final ms = ((this - d) * 60);
    final m = ms.toInt();
    final s = (ms - m) * 60;
    return "$d°${ms.abs()}${NumberFormat("#.##").format(s)}'";
  }
}
